/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkwserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

/* Do ściągnięcia z
 * http://www.jdom.org/dist/binary/jdom-1.1.2.zip
 */
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.*;

/**
 *
 * @author Pawel
 */
public class PKWServerBlocking {
    static BufferedReader bufferedreader;
    static BufferedWriter bufferedwriter;

    private static SSLServerSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException {
	  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
	  KeyStore keyStore = KeyStore.getInstance("JKS");
	 
	  InputStream keyInput = new FileInputStream(pKeyFile);
	  keyStore.load(keyInput, pKeyPassword.toCharArray());
	  keyInput.close();
	  keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
          
	  SSLContext context = SSLContext.getInstance("TLS");
          
	  context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
	  
            
	  return context.getServerSocketFactory();
          
          
    }
    
    private static void parseMessage(String message) {
        String string = null;
        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new StringReader(message));
            Element root = document.getRootElement();
            if(root.getName().equals("msg")) {
                Element content = root.getChild("content");
                if(content.getValue().equals("HELLO")) {
                    Element msg = new Element("msg");
                    Document new_doc = new Document(msg);
                    Element new_content = new Element("content");
                    new_content.addContent("ACK");
                    msg.addContent(new_content);
                    XMLOutputter out = new XMLOutputter();

                    String helloAck = new XMLMessage(out.outputString(new_doc)).toString();

                    bufferedwriter.write(helloAck);
                    bufferedwriter.flush();
                }
            }
        } catch(JDOMException e) {
            System.out.println("Malformed XML");
            System.out.println(e.getMessage());
        } catch(IOException e) {}

    }
    
    public static void main(String[] args) {
        try {
            SSLServerSocketFactory sslserversocketfactory =
                    (SSLServerSocketFactory) getFactory(new File("pkwkeystore.jks"),"bskbsk");
            SSLServerSocket sslserversocket =
                    (SSLServerSocket) sslserversocketfactory.createServerSocket(9999);
              sslserversocket.setUseClientMode(false);
            
            SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
       
            InputStream inputstream = sslsocket.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            bufferedreader = new BufferedReader(inputstreamreader);
            
            
            OutputStream outputstream = sslsocket.getOutputStream();
            OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
            bufferedwriter = new BufferedWriter(outputstreamwriter);
         
            String string = null;
            
            System.out.println("Starting SSL Server");
            while ((string = bufferedreader.readLine()) != null) {
                string = URLDecoder.decode(string, "UTF-8");
                parseMessage(string);
            }
                
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
